package view.audit
{
	import business.BookDelegate;
	import business.CardDelegate;
	
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.CheckBox;
	import mx.controls.ComboBox;
	import mx.controls.DataGrid;
	import mx.controls.Label;
	import mx.controls.LinkButton;
	import mx.controls.SWFLoader;
	import mx.controls.TextInput;
	import mx.core.Application;
	import mx.events.CloseEvent;
	import mx.rpc.events.FaultEvent;
		
	[Bindable]
	public class SetingClass extends VBox
	{
		//public var contentTypesSrc:XML;
		//public var contentTypes:XMLListCollection;
		
		public var m_items:ArrayCollection;
		
		public var page:int;
		public var pagecnt:int;
		public var pageVolume:int;
		public var pageIndices:Array;
			
		public var cmEditorType:ComboBox;
		
		private var selectedIndex:int;
//		public var loaderLock:Boolean;
		
		public var index:int;
				
		private var delegateBook:BookDelegate;
		private var delegateCard:CardDelegate;
		
		private var type:String;	//产品类型
		
		private var range:String;	//列表范围：审核，未审核，全部
		
		//界面元件
		public var item_id:TextInput;
		public var item_bid:TextInput;
		public var item_aid:TextInput;
		public var item_avatar:TextInput;
		public var item_sid:TextInput;
		public var item_mode_label:Label;
		public var item_mode:ComboBox;
		public var item_title:TextInput;
		
		public var item_catalog:TextInput;
		public var item_saveTime:TextInput;
		public var item_fileSize:TextInput;
		public var item_totalTime:TextInput;
		public var item_click:TextInput;
		public var item_flower:TextInput;
		public var item_favorite:TextInput;
		public var item_comment:TextInput;
		public var item_gameid:TextInput;
		public var item_game:TextInput;
		public var item_guildid:TextInput;
		public var item_tag:TextInput;
		public var item_adwords:Object;	

		public var item_audit:CheckBox;
		public var item_share:CheckBox;
		public var item_class:CheckBox;	
		public var item_delete:CheckBox;
		public var commonWords:ComboBox;

		public var item_player:SWFLoader;
		public var item_player_hbox:HBox;
		public var item_box:HBox;
		
		public var myGrid:DataGrid;
		
//		private var conn:LocalConnection;
		
		public function SetingClass()
		{
        	this.delegateBook = new BookDelegate(this);
			this.delegateCard = new CardDelegate(this);
			
			this.type = "book";
			this.range = "unaudit";

			this.page = 0;
			this.index = 0;
			
			getPage(this.page);
			
			this.selectedIndex = -1;
//			this.loaderLock = false;
//			
//			this.conn = new LocalConnection();
//			conn.connect('test');
//			conn.client = this;
		}
		
		public function getPage(page:int=0):void
		{
			if (this.type == "book")
				this.delegateBook.getBooksByAudit(page,this.range);
			else if (this.type == "card")
				this.delegateCard.getCardsByAudit(page,this.range);
			
			if (item_box)
			{
				item_box.enabled = false;
			}	
		}
		
		private function updateItem(ids:Array,update:Object):void
		{
			if (this.type == "book")
			  	this.delegateBook.updateBook(ids,update);
			else if (this.type == "card")
				this.delegateCard.updateCard(ids,update);		
		}

		private function removeItem(page:int,ids:Array):void
		{
			if (this.type == "book")
			  	this.delegateBook.removeBooks(page,ids);
			else if (this.type == "card")
				this.delegateCard.removeCards(page,ids);	
		}

		private function getItemById(ids:Array):void
		{
			if (this.type == "book")
			  	this.delegateBook.getBooksById(ids);
			else if (this.type == "card")
				this.delegateCard.getCardsById(ids);		
		}		
				
		private function refreshPage(result:Object):void
		{
			result = result.result;

			this.page = result.page>0?result.page:0;
			this.pagecnt = result.pagecnt>1?result.pagecnt:1;
			
			this.makePageIndices();

			if (this.type == "book")
			{
			  	this.itemsPrepare(result.books);
			  	item_mode_label.visible = false;
			  	item_mode.visible = false;
			}
			else if (this.type == "card")
			{
				this.itemsPrepare(result.cards);
				item_mode_label.visible = true;
				item_mode.visible = true;
			}				
		}
		
		public function itemsPrepare(items:Array,method:String = "get"):void
		{
			//预处理结果集
			
			if (method == "get")
			{
				this.m_items = new ArrayCollection(items);
			}
			else if (method == "update")
			{
				var newItems:ArrayCollection = new ArrayCollection(items);
				
				for each ( var item1:Object in newItems )
				{
					for(var i:int=0;i<this.m_items.length;++i)
					{
						if (this.m_items[i].id == item1.id)
						{
							this.m_items[i] = item1;
							break;
						}					
					}										 
				}				
			}
			else if (method == "delete")
			{
				for each ( var id:int in items )
				{
					for(var j:int=0;j<this.m_items.length;++j)
					{
						if (this.m_items[j].id == id)
						{
							this.m_items.removeItemAt(j);
							break;
						}					
					}										 
				}					
			}
			
			for each ( var item:Object in this.m_items )
			{
				item.oldid = item.id
				
				if (item._class > 0)
					item.classCheck = true;
				else
					item.classCheck = false;
				
				if (item.share > 0)
					item.shareCheck = true;
				else
					item.shareCheck = false;
				
				if (item.audit > 0)
					item.auditCheck = true;
				else
					item.auditCheck = false;
				
				//TODO: 转换timestamp 到可显示的时间
				item.saveTimeHuman = item.saveTime;
				
				if (item.snap == null)
					item.snap = "http://www.aipai.com/app/www/templates/book/img/bookDefault.gif";						
			}				
		}
		
		public function updatePrepare():Object
		{
			if (myGrid.selectedItem == null)	
			{
				return null;
			}
			var update:Object = new Object();
						
			if(myGrid.selectedItem.id != item_id.text)
			{
				update.id = item_id.text;
				
				//如果更改了ID，需要同步修改
				myGrid.selectedItem.oldid = item_id.text;
				myGrid.selectedItem.id = item_id.text;
			}
				
			if(myGrid.selectedItem.bid != item_bid.text)
				update.bid = item_bid.text;
				
			if(myGrid.selectedItem.aid != item_aid.text)
				update.aid = item_aid.text;
				
			if(myGrid.selectedItem.avatar != item_avatar.text)
				update.avatar = item_avatar.text;
				
			if(myGrid.selectedItem.sid != item_sid.text)
				update.sid = item_sid.text;
			
			if(item_mode.visible && myGrid.selectedItem.mode != item_mode.selectedIndex)
				update.mode = item_mode.selectedIndex;
			
			if(myGrid.selectedItem.title != item_title.text)
				update.title = item_title.text;
				
			if(myGrid.selectedItem.catalog != item_catalog.text)
				update.catalog = item_catalog.text;
			
			if(myGrid.selectedItem.saveTime != item_saveTime.text)
				update.saveTime = item_saveTime.text;
			
			if(myGrid.selectedItem.fileSize != item_fileSize.text)
				update.fileSize = item_fileSize.text;
			
			if(myGrid.selectedItem.totalTime != item_totalTime.text)
				update.totalTime = item_totalTime.text;
			
			if(myGrid.selectedItem.click != item_click.text)
				update.click = item_click.text;

			if(myGrid.selectedItem.flower != item_flower.text)
				update.flower = item_flower.text;
				
			if(myGrid.selectedItem.favorite != item_favorite.text)
				update.favorite = item_favorite.text;
				
			if(myGrid.selectedItem.comment != item_comment.text)
				update.comment = item_comment.text;																																			

			if(myGrid.selectedItem.gameid != item_gameid.text)
				update.gameid = item_gameid.text;	
				
			if(myGrid.selectedItem.game != item_game.text)
				update.game = item_game.text;	
				
			if(myGrid.selectedItem.guildid != item_guildid.text)
				update.guildid = item_guildid.text;	
				
			if(myGrid.selectedItem.tag != item_tag.text)
				update.tag = item_tag.text;	
				
			if(myGrid.selectedItem.adwords != item_adwords.text)
				update.adwords = item_adwords.text;	
				
			if (myGrid.selectedItem.auditCheck != item_audit.selected)
			{
				if (item_audit.selected)
					update.audit = 1;
				else
					update.audit = 0;
			}

			if (myGrid.selectedItem.shareCheck != item_share.selected)
			{
				if (item_share.selected)
					update.share = 1;
				else
					update.share = 0;
			}
																											
			if (myGrid.selectedItem.classCheck != item_class.selected)
			{
				if (item_class.selected)
					update._class = 1;
				else
					update._class = 0;
			}
					
			return update;
		}
		
		public function onSubmit():void
		{	
			if (myGrid.selectedItem == null)	
			{
				Alert.show("请先选择要审核的作品");
				return;
			}
						
			//处理删除
			if (item_delete.selected)
			{	
 				Alert.yesLabel = '确定';
				Alert.noLabel = '取消';
				Alert.buttonWidth = 50;
				Alert.buttonHeight = 18;
	
				Alert.show('您确定要删除吗?',
					'提示',Alert.YES | Alert.NO,null,onDelConfirmed,null,Alert.NO);
				
				return;					
			}
					
			//处理update					
			var update:Object = this.updatePrepare();
            
            if (update == null)
            	return;
            	
            var ids:Array = new Array();
            ids.push(myGrid.selectedItem.oldid);
            
            updateItem(ids,update)
		}

        private function onDelConfirmed(event:CloseEvent):void 
        {
            if (event.detail==Alert.YES)
            {   
            	var ids:Array = new Array();
            	ids.push(myGrid.selectedItem.id);
            	
            	removeItem(this.page,ids);	       		
            }	
        }
        		
		public function onDataGridItemClick():void
		{
			if (myGrid.selectedItem == null )	
			{
				return;
			}
			
			if ( myGrid.selectedIndex == this.selectedIndex )
				return;
			
			this.selectedIndex = myGrid.selectedIndex;
			
			item_box.enabled = true;
			
			commonWords.selectedIndex = 0;
						
			item_delete.selected = false;
			
			Application.application.parameters.info = myGrid.selectedItem.flashVars;
			
//			this.loaderLock = true;
			
			item_player.load();	
		}
		
//		public function unlock():void
//		{
//			this.loaderLock = false;
//		}
		
		public function getBooksForAuditResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
		
		public function getBooksByIdResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
		
		public function removeBooksResult(result:Object, token:Object = null):void
		{
			//Alert.show("删除成功");
			//refreshPage(result);

			result = result.result;
			this.itemsPrepare(result.ids,"delete");					
		}	
		
		public function updateBookResult(result:Object, token:Object = null):void
		{
			result = result.result;
			this.itemsPrepare(result.books,"update");
		}

		public function getCardsForAuditResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
		
		public function getCardsByIdResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
		
		public function removeCardsResult(result:Object, token:Object = null):void
		{
			result = result.result;
			this.itemsPrepare(result.ids,"delete");					
		}	
		
		public function updateCardResult(result:Object, token:Object = null):void
		{
			result = result.result;
			this.itemsPrepare(result.cards,"update");
		}
				
		public function onTypeClick(type:String):void
		{
			this.type = type;
			this.getPage();			
		}
		
		public function onRangeClick(method:String):void
		{
			this.range = method;
			this.getPage();
		}
		
		public function onBtnPreviewClick():void
		{
			this.verticalScrollPosition = item_player_hbox.y;
		}

		public function onBtnBackClick():void
		{
			this.verticalScrollPosition = 0;
		}
				
		public function onSearchId(id:String):void
		{
			if (id.length <= 0)
				return;
				
            var ids:Array = new Array();
            ids.push(id);
            
            getItemById(ids);
		}
		
		public function goto(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.page;
			getPage(page);
		}
		
		private function makePageIndices():void
		{
			var a:Array = new Array();
			a.push({page:0,desc:'首页'});			
			a.push({page:page-1,desc:'前一页'});			
			a.push({page:page+1,desc:'后一页'});
			a.push({page:pagecnt-1,desc:'尾页'});
			this.pageIndices = a;
		} 
				
		public function fault(error:FaultEvent,token:Object = null):void
		{
			Alert.show(error.fault.faultString,'error');
		}
		
		public function onPlayerError():void
		{
			Alert.show("io error");	
		}	
	}	
}
